/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mundo;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Rectangle;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author cesarfgt
 */
public class PanelMundo extends javax.swing.JPanel {

    /**
     * Creates new form PanelMundo
     */
    public int escala;
    private Malla malla;
    private ArrayList<Tramo> PendTramos;    //  Tramos pendients por dibujar
    private ArrayList<Cruce> PendCruce;
    public List<Punto> bots;
    public List<Rectangle> imagesBots;
    public List<TexturePaint> imagesPaintBots;
    private BufferedImage carro = null;
    private BufferedImage semaforo = null;
    private BufferedImage ambulancia = null;
    
    public PanelMundo() {
        try {
            Properties propiedades = new Properties();
            propiedades.load( new FileInputStream( "..//configuracion.properties" ) );

            String imageCar = propiedades.getProperty( "CAR" );
            String imageSem = propiedades.getProperty( "SEM" );
            String imageAmb = propiedades.getProperty( "AMB" );
            carro = PanelMundo.getBufferedImage( imageCar, this );
            semaforo = PanelMundo.getBufferedImage( imageSem, this );
            ambulancia = PanelMundo.getBufferedImage( imageAmb, this );
            
            bots = new ArrayList();
            imagesBots = new ArrayList();
            imagesPaintBots = new ArrayList();

            initComponents();
            this.malla = null;
            this.PendCruce = new ArrayList<Cruce>();
            this.PendTramos = new ArrayList<Tramo>();
            this.escala = 10;
        } catch ( IOException ex ) {
            Logger.getLogger( PanelMundo.class.getName() ).log( Level.SEVERE, null, ex );
        }
    }

    @Override
    public void paintComponent( Graphics g ) {
        super.paintComponent( g );
        Graphics2D g2 = ( Graphics2D ) g; // cast g to Graphics2D  
        // if (this.malla != null) {

        g2.setColor( new Color( 0, 0, 255, 100 ) );

        for ( int i = 0; i < PendCruce.size(); i++ ) {
            Cruce cr = PendCruce.get( i );
            g2.fillRect( ( cr.getInfIz().getX() - 1 ) * escala, ( cr.getInfIz().getY() - 1 ) * escala, ( cr.getSupDer().getX() - cr.getInfIz().getX() + 1 ) * escala, ( cr.getSupDer().getY() - cr.getInfIz().getY() + 1 ) * escala );
        }
        g2.setColor( new Color( 255, 0, 0, 100 ) );
        for ( int i = 0; i < PendTramos.size(); i++ ) {
            Tramo Tr = PendTramos.get( i );
            g2.fillRect( ( Tr.getInfIz().getX() - 1 ) * escala, ( Tr.getInfIz().getY() - 1 ) * escala, ( Tr.getSupDer().getX() - Tr.getInfIz().getX() + 1 ) * escala, ( Tr.getSupDer().getY() - Tr.getInfIz().getY() + 1 ) * escala );
        }

        //}
        //System.out.println( PendTramos.size() + "hola!!" );
        g2.setColor( new Color( 0, 255, 0, 100 ) );
        for ( int i = 0; i < bots.size(); i++ ) {
            Punto p = bots.get( i );
            g2.setPaint( imagesPaintBots.get( i ) );
            g2.fill( imagesBots.get( i ) );
            g2.setPaint( Color.gray );
            g2.draw( imagesBots.get( i ) );
        }
    }

    public List<Punto> getDust() {
        List t = new ArrayList<Cruce>();
        t = getMalla().getListaCruces();
        Cruce c = ( Cruce ) t.get( 0 );



        List Dust = new ArrayList<Punto>();
        Dust.add( c.getInfIz() );
        Dust.add( c.getSupDer() );

        return Dust;
    }

    public void addBot( String alias, int x, int y ) {
        Punto p = new Punto( x, y, alias );
        bots.add( p );

        Rectangle rec = new Rectangle( ( p.getX() - 1 ) * escala, ( p.getY() - 1 ) * escala, ( p.getX() - p.getX() + 1 ) * escala, ( p.getY() - p.getY() + 1 ) * escala );
        imagesBots.add( rec );
        alias=(alias.split("_"))[0];
        
        if(alias.equals("carro")){
            imagesPaintBots.add( new TexturePaint( carro, rec ) );
        }else if(alias.equals("ambulancia")){
            imagesPaintBots.add( new TexturePaint( ambulancia, rec ) );
        }else{
            imagesPaintBots.add( new TexturePaint( semaforo, rec ) );
        }
        malla.getListaPuntos().add(p);
        this.repaint();

    }

    public void move( String alias, int x, int y ) {
        int botIndex = find( this.bots, alias );
        bots.get( botIndex ).setX( x );
        bots.get( botIndex ).setY( y );
        Punto p = bots.get( botIndex );
        if ( botIndex != -1 ) {
            Rectangle rec = new Rectangle( ( p.getX() - 1 ) * escala, ( p.getY() - 1 ) * escala, ( p.getX() - p.getX() + 1 ) * escala, ( p.getY() - p.getY() + 1 ) * escala );
            imagesBots.set( botIndex, rec );
            
            alias=(alias.split("_"))[0];

            if(alias.equals("carro")){
                imagesPaintBots.set( botIndex, new TexturePaint( carro, rec ) );
            }else if(alias.equals("ambulancia")){
                imagesPaintBots.set( botIndex, new TexturePaint( ambulancia, rec ) );
            }else{
                imagesPaintBots.set( botIndex, new TexturePaint( semaforo, rec ) );
            }
        }
        this.repaint();

    }

    private int find( List<Punto> bots, String alias ) {
        for ( int i = 0; i < bots.size(); i++ ) {
            if ( bots.get( i ).getAlias().equals( alias ) ) {
                return i;
            }
        }
        return -1;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings( "unchecked" )
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables

    /**
     * @param malla the malla to set
     */
    public void setMalla( Malla malla ) {
        this.malla = malla;
        this.PendCruce.clear();
        this.PendTramos.clear();

        this.escala = Math.min( this.getPreferredSize().width / this.getMalla().getMaxX(), this.getPreferredSize().height / this.getMalla().getMaxY() );

        for ( int i = 0; i < this.getMalla().getListaCruces().size(); i++ ) {
            this.PendCruce.add( this.getMalla().getListaCruces().get( i ) );
        }
        for ( int i = 0; i < this.getMalla().getListaTramos().size(); i++ ) {
            this.PendTramos.add( this.getMalla().getListaTramos().get( i ) );
        }
    }

    public static BufferedImage getBufferedImage( String imageFile, Component c ) {
        Image image = c.getToolkit().getImage( imageFile );
        waitForImage( image, c );
        BufferedImage bufferedImage = new BufferedImage( image.getWidth( c ), image.getHeight( c ), BufferedImage.TYPE_INT_RGB );
        Graphics2D g2d = bufferedImage.createGraphics();
        g2d.drawImage( image, 0, 0, c );
        return ( bufferedImage );
    }

    public static boolean waitForImage( Image image, Component c ) {
        MediaTracker tracker = new MediaTracker( c );
        tracker.addImage( image, 0 );
        try {
            tracker.waitForAll();
        } catch ( InterruptedException ie ) {
        }
        return ( !tracker.isErrorAny() );
    }

    /**
     * @return the malla
     */
    public Malla getMalla() {
        return malla;
    }
}
